'use client'

import React from 'react'
import { Badge } from '@/components/ui/badge'
import { IconDatabase, IconCloud, IconAlertTriangle } from '@tabler/icons-react'

interface DataSourceIndicatorProps {
  source: 'database' | 'mock' | 'error'
  lastUpdate?: Date
  className?: string
}

export function DataSourceIndicator({
  source,
  lastUpdate,
  className = ''
}: DataSourceIndicatorProps) {
  const getSourceInfo = () => {
    switch (source) {
      case 'database':
        return {
          icon: <IconDatabase className="w-4 h-4" />,
          text: '数据库',
          variant: 'default' as const,
          color: 'text-green-600'
        }
      case 'mock':
        return {
          icon: <IconCloud className="w-4 h-4" />,
          text: '模拟数据',
          variant: 'secondary' as const,
          color: 'text-yellow-600'
        }
      case 'error':
        return {
          icon: <IconAlertTriangle className="w-4 h-4" />,
          text: '连接失败',
          variant: 'destructive' as const,
          color: 'text-red-600'
        }
    }
  }

  const sourceInfo = getSourceInfo()

  return (
    <div className={`flex items-center space-x-2 ${className}`}>
      <Badge variant={sourceInfo.variant} className="flex items-center space-x-1">
        {sourceInfo.icon}
        <span>{sourceInfo.text}</span>
      </Badge>
      {lastUpdate && (
        <span className="text-xs text-white">
          更新: {lastUpdate.toLocaleTimeString('zh-CN')}
        </span>
      )}
    </div>
  )
}

// 数据源状态管理 Hook
export function useDataSource() {
  const [source, setSource] = React.useState<'database' | 'mock' | 'error'>('mock')
  const [lastUpdate, setLastUpdate] = React.useState<Date | undefined>()
  const [isLoading, setIsLoading] = React.useState(false)

  const updateSource = (newSource: 'database' | 'mock' | 'error', updateTime?: Date) => {
    setSource(newSource)
    setLastUpdate(updateTime || new Date())
    setIsLoading(false)
  }

  const setLoading = (loading: boolean) => {
    setIsLoading(loading)
  }

  return {
    source,
    lastUpdate,
    isLoading,
    updateSource,
    setLoading
  }
}
